package com.dapeis.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.jws.soap.SOAPBinding.Use;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import com.ag.core.exception.SysTipsException;
import com.ag.core.utils.AgAssert;
import com.ag.utils.json.AGsonBuilder;
import com.ag.utils.json.GsonUtils;
import com.aliyun.oss.internal.ResponseParsers.GetBucketAclResponseParser;
import com.dapeis.core.utils.DBConfigUtils;
import com.dapeis.domain.Collocation;
import com.dapeis.domain.User;
import com.dapeis.domain.ext.CollocationExt;
import com.dapeis.domain.ext.UserExt;
import com.dapeis.domain.msg.Message;
import com.dapeis.exception.tim.TIMServiceExcepion;
import com.dapeis.im.tim.TIMConfig;
import com.dapeis.im.tim.TIMSYSTAG;
import com.dapeis.im.tim.TIMSigUtil;
import com.dapeis.im.tim.TIMURL;
import com.dapeis.im.tim.TIMUtil;
import com.dapeis.im.tim.req.TIMAttribute;
import com.dapeis.im.tim.req.TIMFriend;
import com.dapeis.im.tim.req.TIMTag;
import com.dapeis.im.tim.req.accout.TIMAccount;
import com.dapeis.im.tim.req.attr.TIMAttributeInfo;
import com.dapeis.im.tim.req.friend.TIMCheckFriend;
import com.dapeis.im.tim.req.friend.TIMFriendInfo;
import com.dapeis.im.tim.req.message.TIMMessage;
import com.dapeis.im.tim.req.message.TIMMessageBody;
import com.dapeis.im.tim.req.message.TIMMessageContent;
import com.dapeis.im.tim.req.signature.TIMSignature;
import com.dapeis.im.tim.req.tag.TIMTAGInfo;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

/**
 * @author 作者 E-mail: hzyuanyong@126.com
 * @version 创建时间：2017年5月17日 下午9:12:22 TIM Services类说明
 */
@Service
public class TIMService {

    @Resource
    UserService userService;
    @Resource
    CollocationService collocationService;

    /**
     * 添加用户
     * 
     * @param user
     * @return
     */
    public boolean importAccount(User user) {
	TIMAccount userAccount = new TIMAccount(
		TIMUtil.getWxUserIdentifier(user.getId()), user.getNickName(),
		user.getHeadImg());
	JsonObject reslut = doPOST(AGsonBuilder.create()
		.toJsonTree(userAccount).toString(),
		TIMURL.get(TIMURL.IMPORT_ACCOUNT));
	if (checkResult(reslut)) {
	    user.setRegTIMDate(new Date().getTime() / 1000);
	    return userService.updateByPrimaryKeySelective(user) > 0;
	}
	return false;
    }

    /**
     * 添加搭配师
     * 
     * @param collocation
     * @return
     */
    public boolean importAccount(Collocation collocation) {
	TIMAccount collocationAccout = new TIMAccount(
		TIMUtil.getDPSUserIdentifier(collocation.getId()),
		collocation.getNickName(),
		DBConfigUtils.getFullImgPath(collocation.getHeadImg()));
	JsonObject reslut = doPOST(
		AGsonBuilder.create().toJsonTree(collocationAccout).toString(),
		TIMURL.get(TIMURL.IMPORT_ACCOUNT));
	if (checkResult(reslut)) {
	    collocation.setRegTimDate(new Date().getTime() / 1000);
	    return collocationService.updateByPrimaryKeySelective(collocation) > 0;
	}
	return false;
    }

    /**
     * 更新搭配师资料(目前只有搭配师更新资料)
     * 
     * @param collocation
     * @return
     */
    public boolean updateAccout(Collocation collocation) {
	if (collocation.getRegTimDate() == null) {
	    // 表示TIM未注册,直接进行注册
	    return importAccount(collocation);
	} else {
	    // 更新头像和昵称
	    List<TIMTAGInfo> list = new ArrayList<TIMTAGInfo>();
	    list.add(new TIMTAGInfo(TIMSYSTAG.HEADIMG, DBConfigUtils
		    .getFullImgPath(collocation.getHeadImg())));
	    list.add(new TIMTAGInfo(TIMSYSTAG.NICKNAME, collocation
		    .getNickName()));
	    TIMTag tag = new TIMTag(TIMUtil.getDPSUserIdentifier(collocation
		    .getId()), list);

	    JsonObject resultJson = doPOST(AGsonBuilder.create()
		    .toJsonTree(tag).toString(),
		    TIMURL.get(TIMURL.IM_PROFILE_SET));
	    return checkResult(resultJson);
	}
    }

    /**
     * 添加好友关系
     * 
     * @param collocation
     * @param user
     * @return
     */
    public boolean addFriend(Integer collocationId, Integer userId) {
	if (!checkFriend(collocationId, userId)) {
	    TIMFriend timFriend = new TIMFriend(
		    TIMUtil.getDPSUserIdentifier(collocationId),
		    new TIMFriendInfo(
			    TIMUtil.getWxUserIdentifier(userId),
			    "AddSource_Type_"
				    + TIMUtil
					    .getDPSUserIdentifier(collocationId)));
	    JsonObject resultJson = doPOST(
		    AGsonBuilder.create().toJsonTree(timFriend).toString(),
		    TIMURL.get(TIMURL.IM_ADD_FRIEND));

	    return checkResult(resultJson);
	}
	return true;
    }

    /**
     * 获取搭配师好友 true 存在好友关系 ,false 不存在
     * 
     * @param collocation
     */
    public boolean checkFriend(Integer collocationId, Integer userId) {
	User user = userService.selectByPrimaryKey(userId);
	Collocation collocation = collocationService
		.selectByPrimaryKey(collocationId);
	if (null == user.getRegTIMDate()) {
	    importAccount(user);
	}
	if (null == collocation.getRegTimDate()) {
	    importAccount(collocation);
	}
	TIMCheckFriend checkFriend = new TIMCheckFriend(collocationId, userId);

	JsonObject resultJson = doPOST(
		AGsonBuilder.create().toJsonTree(checkFriend).toString(),
		TIMURL.get(TIMURL.IM_CHECK_FRIEND));
	if (checkResult(resultJson)) {
	    JsonArray resultArray = resultJson.get("InfoItem").getAsJsonArray();
	    if (null != resultArray) {
		for (Iterator iterator = resultArray.iterator(); iterator
			.hasNext();) {
		    JsonObject jsonObject = (JsonObject) iterator.next();
		    if (null != jsonObject && jsonObject.has("Relation")) {
			if (jsonObject.get("Relation").getAsString()
				.equals("CheckResult_Type_BothWay"))
			    return true;
		    }
		}
	    }
	}
	return false;
    }

    /**
     * 获取用户签名信息
     * 
     * @param user
     * @return
     */
    public JsonObject getWxUserSignature(User user) {

	TIMSignature userSingSignature = new TIMSignature(
		TIMUtil.getWxUserIdentifier(user.getId()),
		TIMSigUtil.getSigsignature(TIMUtil.getWxUserIdentifier(user
			.getId())), user.getNickName(), user.getHeadImg());
	return AGsonBuilder.create().toJsonTree(userSingSignature)
		.getAsJsonObject();
    }

    /**
     * 获取搭配师用户签名信息
     * 
     * @param collocation
     * @return
     */
    public JsonObject getDPSCollocationSignature(Collocation collocation) {

	TIMSignature timSignature = new TIMSignature(
		TIMUtil.getDPSUserIdentifier(collocation.getId()),
		TIMSigUtil.getSigsignature(TIMUtil
			.getDPSUserIdentifier(collocation.getId())),
		collocation.getNickName(),
		DBConfigUtils.getFullImgPath(collocation.getHeadImg()));
	return AGsonBuilder.create().toJsonTree(timSignature).getAsJsonObject();
    }

    /**
     * 添加系统属性值
     * 
     * @return
     */
    public boolean addSystemTIMAttribute() {
	JsonObject jsonObject = new JsonObject();
	Map<String, String> attMap = new HashMap<String, String>();
	// attMap.put("0", TIMConfig.Attribute.HEADURL);
	attMap.put("1", TIMConfig.Attribute.SEX);
	attMap.put("2", TIMConfig.Attribute.AGE);
	attMap.put("3", TIMConfig.Attribute.HONOR);
	attMap.put("4", TIMConfig.Attribute.STYLE);

	jsonObject.add("AttrNames", AGsonBuilder.create().toJsonTree(attMap));
	JsonObject resultJson = doPOST(jsonObject.toString(),
		TIMURL.get(TIMURL.IM_SET_SYS_ATTR_NAME));
	return checkResult(resultJson);
    }

    public JsonObject getSysTIMAttribute() {
	JsonObject json = new JsonObject();// 构造{}空对象
	JsonObject resultJson = doPOST(json.toString(),
		TIMURL.get(TIMURL.IM_GET_SYS_ATTR_NAME));
	if (checkResult(resultJson))
	    return resultJson;
	return null;
    }

    /**
     * 用户添加属性值
     * 
     * @param user
     * @return
     */
    public boolean adddUserTIMAttribute(UserExt userExt) {

	Map<String, String> attribuMap = new HashMap<String, String>();
	attribuMap.put(TIMConfig.Attribute.AGE, null == userExt
		.getUserInformation() ? new String().toString() : userExt
		.getUserInformation().getSex().toString());
	attribuMap.put(TIMConfig.Attribute.SEX, null == userExt
		.getUserInformation() ? new String().toString() : userExt
		.getUserInformation().getSex().toString());
	TIMAttributeInfo timAttributeInfo = new TIMAttributeInfo(
		TIMUtil.getWxUserIdentifier(userExt.getId()), attribuMap);
	TIMAttribute timAttribute = new TIMAttribute(timAttributeInfo);

	JsonObject resultJson = doPOST(
		AGsonBuilder.create().toJsonTree(timAttribute).toString(),
		TIMURL.get(TIMURL.IM_SET_USER_ATTR));
	return checkResult(resultJson);
    }


    /**
     * 搭配师添加属性值
     * 
     * @param collocation
     * @return
     */
    public boolean addCollocationTIMAttirbute(CollocationExt collocationExt) {
	Map<String, String> attribuMap = new HashMap<String, String>();
	attribuMap.put(TIMConfig.Attribute.AGE, null == collocationExt
		.getCollocationInformation() ? new String().toString()
		: collocationExt.getCollocationInformation().getSex()
			.toString());
	attribuMap.put(TIMConfig.Attribute.HONOR, collocationExt.getHonor());
	attribuMap
		.put(TIMConfig.Attribute.STYLE, collocationExt.getGoodStyle());
	TIMAttributeInfo timAttributeInfo = new TIMAttributeInfo(
		TIMUtil.getDPSUserIdentifier(collocationExt.getId()),
		attribuMap);
	TIMAttribute timAttribute = new TIMAttribute(timAttributeInfo);

	JsonObject resultJson = doPOST(
		AGsonBuilder.create().toJsonTree(timAttribute).toString(),
		TIMURL.get(TIMURL.IM_SET_USER_ATTR));
	return checkResult(resultJson);
    }

    /**
     * 具体执行
     * 
     * @param paramJson
     * @param url
     * @return
     */
    private JsonObject doPOST(String paramJson, String url) {
	CloseableHttpClient client = null;
	CloseableHttpResponse response = null;
	JsonObject reslutJson = null;
	StringEntity entity = new StringEntity(paramJson, "utf-8");// 解决中文乱码问题
	entity.setContentEncoding("UTF-8");
	entity.setContentType("application/json");
	HttpPost httpPost = new HttpPost(url);
	httpPost.setEntity(entity);
	client = HttpClients.createDefault();
	try {
	    response = client.execute(httpPost);
	    if (response != null && response.getEntity() != null) {
		String resData = EntityUtils.toString(response.getEntity());
		reslutJson = GsonUtils.parseJsonObject(resData);
	    }
	} catch (TIMServiceExcepion e) {
	    e.printStackTrace();
	} catch (IOException e) {
	    e.printStackTrace();
	}
	return reslutJson;
    }

    /**
     * 判断返回结果 true 成功,false 失败
     */
    private boolean checkResult(JsonObject json) {
	if (json.has("ActionStatus")
		&& json.get("ActionStatus").getAsString().equals("OK")) {
	    return true;
	} else if (json.has("ActionStatus")
		&& json.get("ActionStatus").getAsString().equals("FAIL")) {
	    throw new TIMServiceExcepion(json.get("ErrorInfo").getAsString());
	}
	throw new TIMServiceExcepion();
    }

}
